package com.education.common.exception;

import com.education.common.util.Result;
import com.education.common.util.ResultCode;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.UnauthenticatedException;
import org.apache.shiro.authz.UnauthorizedException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MaxUploadSizeExceededException;

/**
 * 捕获系统异常
 * @author 余一
 * @date 2021/9/13  16:59
 */
@ControllerAdvice
@Slf4j
public class SystemExceptionHandler {

    @ExceptionHandler(Exception.class)
    @ResponseBody
    public Result resolveException(Exception ex){
        log.error("系统异常",ex);
        if (ex instanceof BusinessException) {
            BusinessException businessException = (BusinessException) ex;

            if (businessException.getResult() != null) {
                return businessException.getResult();
            }
            return Result.fail(businessException.getResultCode().getCode(),businessException.getResult().getMessage());
        }else if (ex instanceof UnauthorizedException || ex instanceof UnauthenticatedException){
            return Result.fail(ResultCode.NO_PERMISSION,"权限不足，无法访问");
        }else if (ex instanceof MaxUploadSizeExceededException){
            return Result.fail(ResultCode.NO_PERMISSION,"文件不能超过200M, 请重新上传");
        }
        return Result.fail(ResultCode.FAIL,"系统异常");
    }

}
